import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTimeStamp } from './auth'
import router from '@/router'

const timeOut = 2 * 24 * 60 * 60 * 1000
const checkOutTime = () => {
  return Date.now() - getTimeStamp() > timeOut
}
// create an axios instance
const service = axios.create({
  baseURL: 'http://geek.itheima.net', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    'Content-Type': 'application/json'
  },
  timeout: 5000 // request timeout
})

service.interceptors.request.use(
  (config) => {
    const token = store.getters.token
    if (token) {
      if (checkOutTime()) {
        console.log('失效')
        store.dispatch('user/logOut')
        router.push('/login')
        return Promise.reject(new Error(' token失效'))
      }
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => {
    console.log('请求错误')
    return Promise.reject(err)
  }
)
service.interceptors.response.use(
  (response) => {
    const { message, data, success } = response.data
    if (success || message === 'OK') {
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  (err) => {
    if (err.response.status === 401) {
      store.dispatch('user/logOut')
      router.push('/login')
    }
    return Promise.reject(err)
  }
)

export default service
